package com.hzp.net.client;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;


@Slf4j
class ConnectHandler extends Handler implements Runnable {
    public ConnectHandler(SelectionKey key, Selector selector) {
        super(key,selector);
    }

    @Override
    public void run() {
        //处理连接
        SocketChannel channel = (SocketChannel) getKey().channel();   //通过key找到对应的channel
        try {
            channel.finishConnect(); // 完成连接
            getKey().interestOps(getKey().interestOps() & ~SelectionKey.OP_CONNECT); // 取消监听连接就绪（否则selector会不断提醒连接就绪）
            getKey().interestOps(getKey().interestOps() | SelectionKey.OP_READ | SelectionKey.OP_WRITE); // 监听读就绪和写就绪
            log.info("连接服务器成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
